import React from 'react';
import { inject, observer } from 'mobx-react';
import { observable, action, toJS } from 'mobx';
import { WeaPopoverHrm, WeaDialog, WeaNewScroll, WeaTools, WeaTop, WeaAlertPage, WeaDialogFooter,WeaLocaleProvider, WeaRightMenu, WeaMoreButton, WeaCheckbox } from 'ecCom';
import { Button, Spin, Modal,message } from 'antd';
import Collapse from './collapse.js'
import Create from './create.js'
import Preview from './preview.js';
import Share from './share.js';
import './index.less';
import {WeaLogView} from 'comsMobx';
const WeaLogViewComp = WeaLogView.Component;
const getLabel = WeaLocaleProvider.getLabel;
const ButtonGroup = Button.Group;
@inject('myWorkPlanStore')
@inject('createWorkPlanStore')
@inject('routing')
@observer
class WorkPlanCreate extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      test: '',
      createCondition: '',//目的:外部组件调用传值,目前这个属性只针对时间
      authConditions: [],
      authVisible: false,
      activeKey: '1',
      spinning: true,
      finishLoading:false,
      deleteLoading:false,
      logvisible: false,
      
      needHideBack:false,
      isfromchatshare:this.props.isfromchatshare,
      sharer:this.props.sharer
    }
  }

  componentDidMount() {
    const {initWorkpln, setParam}=this.props.createWorkPlanStore;
    initWorkpln();
    if(this.props.visible){
      this.setState({ visible: true })
      }

    //
    let crmid = '';
    if(this.props.crmIDs && typeof this.props.crmIDs == 'object'){
      let crmids = this.props.crmIDs.map((item,index)=>{
        return item.id
      })
      crmid = crmids.join(',')
    }else if(this.props.crmIDs && typeof this.props.crmIDs == 'string'){
      crmid = this.props.crmIDs;
    }
    if(this.props.crmid && typeof this.props.crmid == 'object'){
      let crmids = this.props.crmid.map((item,index)=>{
        return item.id
      })
      crmid = crmids.join(',')
    }else if(this.props.crmid && typeof this.props.crmid == 'string'){
      crmid = this.props.crmid;
    }
    if(this.props.workPlanTypeOptions && this.props.workPlanTypeOptions == '3' && crmid != ''){
      setParam({fromType:'crm'});
    }

    this.getData(this.props);
  }

  componentWillReceiveProps(nextProps) {
    const {type,setParam}=this.props.createWorkPlanStore;
    let needLoad=false;
    if (type != nextProps.type) {
      needLoad=true;
    }
    if (this.state.activeKey != nextProps.activeKey) {
      this.setState({ activeKey: nextProps.activeKey })
    }
    if (this.state.visible != nextProps.visible) {
      if (this.props.visible == false && nextProps.visible == true) {
        needLoad=true;
      }
      this.setState({ visible: nextProps.visible })
    }
    let crmid = '';
    if(nextProps.crmIDs && typeof nextProps.crmIDs == 'object'){
      let crmids = nextProps.crmIDs.map((item,index)=>{
        return item.id
      })
      crmid = crmids.join(',')
    }else if(nextProps.crmIDs && typeof nextProps.crmIDs == 'string'){
      crmid = nextProps.crmIDs;
    }
    if(nextProps.crmid && typeof nextProps.crmid == 'object'){
      let crmids = nextProps.crmid.map((item,index)=>{
        return item.id
      })
      crmid = crmids.join(',')
    }else if(nextProps.crmid && typeof nextProps.crmid == 'string'){
      crmid = nextProps.crmid;
    }
    if(nextProps.workPlanTypeOptions && nextProps.workPlanTypeOptions == '3' && crmid != ''){
      setParam({fromType:'crm'});
    }else{
      setParam({fromType:''});
    }
    if(needLoad){
      this.getData(nextProps);
    }
  }

  componentWillUnmount() {
    //组件卸载时一般清理一些状态
    // const { coworkCollectStore } = this.props;

    // coworkCollectStore.setShowSearchAd(false);
    // coworkCollectStore.saveSearchParamsFields();
    const { setStatusParams }=this.props.myWorkPlanStore;
    setStatusParams({
      createVisible: false,
      createType: 'preview',
      workPlanId: '',
    });
  }

  componentDidUpdate() {
    const { isSingle = false } = this.props; 
    const {setParam} = this.props.createWorkPlanStore;
    !isSingle&&setParam({scrollHeight: parseInt(this.refs.wea_Dialog.state.height, 10)});
  }

  getData = nextProps => {
    this.setState({ spinning: true });
    const {setCreateCondition,setParam,setSecretLevel,setChkStatus,getBaseFields,getViewFields,getExchangeList,fromType}= this.props.createWorkPlanStore
    setParam({type:nextProps.type});
    if (nextProps.type == 'preview' || nextProps.type == 'share') {
      setParam({ workPlanId:nextProps.workPlanId })
      this.setState({activeKey: nextProps.activeKey})
      getViewFields({workid: nextProps.workPlanId,isfromchatshare:nextProps.isfromchatshare || '',sharer:nextProps.sharer || '' , fromType: fromType },()=>{
        this.setState({ spinning: false })
        getExchangeList({workplanid: nextProps.workPlanId,isfromchatshare:nextProps.isfromchatshare || '',sharer:nextProps.sharer || '' })
      })
    }else  if (nextProps.type == 'create') {
      let bD = '', bT = '', eD='', eT='';
      let today= this.getNowDateStr();
      let nowTime=this.getNowTimeStr();
      if (nextProps.createConditionParams.length > 0) {
        bD=nextProps.createConditionParams[2]||today;
        bT=nextProps.createConditionParams[3]||'';
        if(bT==''){ //开始时间为空
          if(bD==today){ //日期为今天. 取当前时间
            bT=nowTime;
          }else{ //日期不是今天. 取日历范围
            bT='';
          }
        }
        eD=nextProps.createConditionParams[4]||bD;
        eT=nextProps.createConditionParams[5]||'';
      }
      let crmid = '',docid='',projectid='',taskid='',requestid='';
      if(nextProps.docid && typeof nextProps.docid == 'object'){
        let docids = nextProps.docid.map((item,index)=>{
          return item.id
        })
        docid = docids.join(',')
      }else if(nextProps.docid && typeof nextProps.docid == 'string'){
        docid = nextProps.docid
      }
      if(nextProps.crmIDs && typeof nextProps.crmIDs == 'object'){
        let crmids = nextProps.crmIDs.map((item,index)=>{
          return item.id
        })
        crmid = crmids.join(',')
      }else if(nextProps.crmIDs && typeof nextProps.crmIDs == 'string'){
        crmid = nextProps.crmIDs;
      }
      if(nextProps.crmid && typeof nextProps.crmid == 'object'){
        let crmids = nextProps.crmid.map((item,index)=>{
          return item.id
        })
        crmid = crmids.join(',')
      }else if(nextProps.crmid && typeof nextProps.crmid == 'string'){
        crmid = nextProps.crmid;
      }
      if(nextProps.projectid && typeof nextProps.projectid == 'object'){
        let projectids = nextProps.projectid.map((item,index)=>{
          return item.id
        })
        projectid = projectids.join(',')
      }else if(nextProps.projectid && typeof nextProps.projectid == 'string'){
        projectid = nextProps.projectid;
      }
      if(nextProps.taskid && typeof nextProps.taskid == 'object'){
        let taskids = nextProps.taskid.map((item,index)=>{
          return item.id
        })
        taskid = taskids.join(',')
      }else if(nextProps.taskid && typeof nextProps.taskid == 'string'){
        taskid = nextProps.taskid;
      }
      if(nextProps.requestid && typeof nextProps.requestid == 'object'){
        let requestids = nextProps.requestid.map((item,index)=>{
          return item.id
        })
        requestid = requestids.join(',')
      }else if(nextProps.requestid && typeof nextProps.requestid == 'string'){
        requestid = nextProps.requestid;
      }
      getBaseFields({selectUser: nextProps.selectUser || nextProps.resourceid,workPlanTypeOptions:nextProps.workPlanTypeOptions||'',
        docid:docid, crmid:crmid,projectid:projectid, taskid:taskid, requestid:requestid,
        beginDate:bD, beginTime:bT, endDate:eD, endTime:eT,fromType:fromType},()=>{this.setState({ spinning: false });})
    }else if(nextProps.type == 'edit'){
      if(nextProps.needHideBack){
        this.setState({needHideBack:true});
      }
      nextProps.workPlanId>0 && this.doEdit()
    }
  }

  getNowDateStr=()=>{
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    if (month < 10) {
        month = "0" + month;
    }
    let day = date.getDate();
    if (day < 10) {
        day = "0" + day;
    }
    return year+"-"+month+"-"+day;
  }

  getNowTimeStr=()=>{
    let date = new Date();
    //获取时间
    let hour = "00" + date.getHours();
    hour = hour.substr(hour.length - 2);
    let minute = "00" + date.getMinutes();
    minute = minute.substr(minute.length - 2);
    return hour+":"+minute;
  }

  previewChangeTab = (e) => {
    this.props.changeTab(e);
  }

  getPreview = () => {
    const {hasRight, hasSecretRight, hasDataRight}= this.props.createWorkPlanStore
    let warningLabel = ''
    if(!hasRight){
      warningLabel = getLabel(382663,'暂无权限')
    }
    if(!hasSecretRight){
      warningLabel = getLabel(501082,'对不起，您的人员密级不足以查看该内容')
    }
    if(!hasDataRight){
      warningLabel = getLabel(508094,'该日程已被删除！')
    }
    let com = hasRight&&hasSecretRight&&hasDataRight ? (
      <Preview ecId={`${this && this.props && this.props.ecId || ''}_Preview@d2xdd1`} activeKey={this.state.activeKey}
        changeTab={this.previewChangeTab}
        workPlanId={this.props.workPlanId}
        exchangeList={this.props.createWorkPlanStore.exchangeList}
        isfromchatshare={this.state.isfromchatshare}
        sharer={this.state.sharer}/>
    ) : (
        <div style={{position: 'absolute', width:'100%', top:'40%',}}>
          <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@avcakj`}>
            <div >
              {warningLabel}
          </div>
          </WeaAlertPage>
        </div>
      )
    return com;
  }
  getRightMenu = () => {
    let btnArr = [];

    const { type } = this.props.createWorkPlanStore;
    if (type == 'preview') {
        const {hasRight, hasSecretRight, hasDataRight, previewButtons}= this.props.createWorkPlanStore

        if(previewButtons && previewButtons.length > 0 && hasRight && hasSecretRight&&hasDataRight){
            if(previewButtons.some((element) => { return element.method == 'doEdit' })){
                btnArr.push({
                    key: 'save',
                    content: previewButtons.map((e) => { if (e.method == 'doEdit') { return e.title } else { return '' } }),
                    icon: <i className='icon-coms-edit' />,
                    onClick: this.doEdit,
                  })
            }
            if(previewButtons.some((element) => { return element.method == 'doFinish' })){
                btnArr.push({
                    key: 'doFinish',
                    content:previewButtons.map((e) => { if (e.method == 'doFinish') { return e.title } else { return '' } }),
                    icon: <i className='icon-coms-Approval' />,
                    onClick: this.doFinish,
                  })
            }
            if(previewButtons.some((element) => { return element.method == 'doDelete' })){
                btnArr.push({
                    key: 'doDelete',
                    content: previewButtons.map((e) => { if (e.method == 'doDelete') { return e.title } else { return '' } }),
                    icon: <i className='icon-coms-delete' />,
                    onClick: this.doDelete,
                  })
            }
            if(previewButtons.some((element) => { return element.method == 'doShare' })){
                btnArr.push({
                    key: 'doShare',
                    content: previewButtons.map((e) => { if (e.method == 'doShare') { return e.title } else { return '' } }),
                    icon: <i className='icon-coms-Batch-sharing' />,
                    onClick: this.doShare,
                  })
            }
            if(previewButtons.some((element) => { return element.method == 'chatShare' })){
              btnArr.push({
                  key: 'chatShare',
                  content: previewButtons.map((e) => { if (e.method == 'chatShare') { return e.title } else { return '' } }),
                  icon: <i className='icon-coms-Batch-sharing' />,
                  onClick: this.chatShare,
                })
            }
            if(previewButtons.some((element) => { return element.method == 'doValuate' })){
                btnArr.push({
                    key: 'doValuate',
                    content: previewButtons.map((e) => { if (e.method == 'doValuate') { return e.title } else { return '' } }),
                    icon: <i className='icon-coms-Preservation' />,
                    onClick: this.doValuate,
                  })
            }
            if(previewButtons.some((element) => { return element.method == 'doConvert' })){
                btnArr.push({
                    key: 'doConvert',
                    content: previewButtons.map((e) => { if (e.method == 'doConvert') { return e.title } else { return '' } }),
                    icon: <i className='icon-coms-Preservation' />,
                    onClick: this.doConvert,
                  })
            }
            if(previewButtons.some((element) => { return element.method == 'doLog' })){
                btnArr.push({
                    key: 'doLog',
                    content: previewButtons.map((e) => { if (e.method == 'doLog') { return e.title } else { return '' } }),
                    icon: <i className='icon-coms-Print-log' />,
                    onClick: this.toggleLog,
                  })
            }
        }
      }
      if (type == 'create') {
        btnArr.push({
            key: 'handleSubmit',
            content: getLabel(30986,'保存'),
            icon: <i className='icon-coms-Preservation' />,
            onClick: this.handleSubmit,
          })
      }
      if (type == 'edit') {
        btnArr.push({
            key: 'handleSubmit',
            content: getLabel(30986,'保存'),
            icon: <i className='icon-coms-Preservation' />,
            onClick: this.editSave,
          })
         if(!this.state.needHideBack){
          btnArr.push({
            key: 'doReturn',
            content: getLabel(1290,'返回'),
            icon: <i className='icon-coms-Reset' />,
            onClick: this.doReturn,
          })
        }
      }
    
    return btnArr;
  }

  singleBtns = () => {
    const { isBtnDown } = this.props;
    let btns = this.getButton();
    btns.push(
      <WeaMoreButton ecId={`${this && this.props && this.props.ecId || ''}_WeaMoreButton@py1r99@isBtnDown`} className={isBtnDown ? '':'workplan-single-container'} datas={this.getRightMenu()} />
    );
    return btns;
  }

  render() {
    const { isSingle = false, isBtnDown } = this.props; //isSingle:判断是单页还是弹框
    let { visible, createCondition, authVisible, authConditions, activeKey, spinning} = this.state;
    let {setSingle,type,logStore,logType,logSmallType,targetId}= this.props.createWorkPlanStore;
    setSingle(isSingle);
    let isEdit = type == 'edit' ? true : false;
    let title = type == 'create' ? getLabel(18481,'新建日程') : type == 'preview' ? getLabel(384902,'查看日程') : type == 'edit' ? getLabel(384903,'编辑日程') : getLabel(20221,'日程共享设置');
    if(isSingle && this.props.type == 'create'){
      title = getLabel(18481,'新建日程') ;
    }
    if(isSingle){
      document.title = title;
      return (
        <div className='workPlan-dialog-single' style={{height: '100%'}}>
          <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@to271n`}
            title={title}
            icon={<i className='icon-coms-schedule' />}
            iconBgcolor='#7734FF'
            buttons={isBtnDown ? [] : this.singleBtns()}
          >
            <div className='dialog-single-content' style={{ height: isBtnDown ? 'calc(100% - 53px)' : '100%'}}>
              <WeaPopoverHrm ecId={`${this && this.props && this.props.ecId || ''}_WeaPopoverHrm@ldxdta`} inDialog={false}>
                <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@dtlnsg`} spinning={spinning} style={{ height: '100%' }}>
                  {type == 'create' || type == 'edit' ? <Create ecId={`${this && this.props && this.props.ecId || ''}_Create@iuvx8t`} ref="workPlanCreate" isEdit={isEdit} isSingle={isSingle}/> : ''}
                  {type == 'preview' && visible && this.getPreview()}
                  {type == 'share' ? <Share ecId={`${this && this.props && this.props.ecId || ''}_Share@wrer6q`} callbackState={this.callbackState} spinning={this.spinning} workPlanId={this.props.workPlanId} onCancel={this.onCancel} visible={authVisible} conditions={authConditions} isSingle={isSingle} /> : ''}
                </Spin>
              </WeaPopoverHrm>
              <WeaLogViewComp ecId={`${this && this.props && this.props.ecId || ''}_WeaLogViewComp@8uwy8a`} visible={this.state.logvisible} onCancel={this.toggleLog} logStore={logStore} 
                logType={logType} logSmallType={logSmallType}
                targetId={targetId}/>
            </div>
            {isBtnDown && <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@evy3rc`}
              className='isBtnDown'
              buttons={this.singleBtns()}
            />}
          </WeaTop>
        </div>
      )
    }else {
      return (
        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@mv5b0c`}
          ref={'wea_Dialog'}
          visible={visible}
          title={title}
          icon="icon-coms-schedule"
          iconBgcolor="#7734FF"
          className="createWorkPlan"
          buttons={this.getButton()}
          style={{ width: '785px', height: '500px' }}
          onCancel={this.onlyClose}
          moreBtn={{
            datas : this.getRightMenu(),
            collectParams: {
              favname:'新建日程',
              favouritetype: 2,
              objid: 0,
              importantlevel:1,
            }
          }}
        >
            <WeaPopoverHrm ecId={`${this && this.props && this.props.ecId || ''}_WeaPopoverHrm@hhjtdh`} inDialog={false}>
              <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@0dtu6p`} spinning={spinning} style={{ height: '100%' }}>
              <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@rkgo22`} 
                datas={this.getRightMenu()}
                collectParams={{
                  favname:'新建日程',
                  favouritetype: 2,
                  objid: 0,
                  importantlevel:1,
                }}
                >
                  {type == 'create' || type == 'edit' ? <Create ecId={`${this && this.props && this.props.ecId || ''}_Create@kim2ip`} ref="workPlanCreate" isEdit={isEdit} createCondition={createCondition} /> : ''}
                  {type == 'preview' && visible && this.getPreview()}
                  {type == 'share' ? <Share ecId={`${this && this.props && this.props.ecId || ''}_Share@udvbuo`} callbackState={this.callbackState} spinning={this.spinning} workPlanId={this.props.workPlanId} onCancel={this.onCancel} visible={authVisible} conditions={authConditions} workPlanId={this.props.workPlanId}  rightButton={this.doReturn} changeOneWeekDatas={this.props.changeOneWeekDatas} /> : ''}
                </WeaRightMenu>
              </Spin>
            </WeaPopoverHrm>
            <WeaLogViewComp ecId={`${this && this.props && this.props.ecId || ''}_WeaLogViewComp@sg84n5`} visible={this.state.logvisible} onCancel={this.toggleLog} logStore={logStore} 
            logType={logType} logSmallType={logSmallType}
            targetId={targetId}/>
        </WeaDialog>
      )
    }
  }

  toggleLog = () => {
    this.setState({logvisible: !this.state.logvisible});
  }

  doClose = () => {
    this.setState({ createCondition: '' });
    this.props.doClose && this.props.doClose()
  }

  onlyClose = () => {
    let { type } = this.state;
    if (type != 'share') {
      this.setState({ createCondition: '' });
      this.props.onlyClose && this.props.onlyClose()
    } else if (type == 'share') {//共享页面右上角的关闭，点击效果是回到查看日程页面
      this.doReturn();
    }
    this.setState({ visible: false });
  }

  getButton = () => {
    const { type } = this.props.createWorkPlanStore;
    const{saveLoading}=this.props.myWorkPlanStore;
    if (type == 'preview') {
      const {hasRight, hasSecretRight, hasDataRight, previewButtons}= this.props.createWorkPlanStore
      let buttons_create = [];
      if(previewButtons && previewButtons.length > 0) {
        previewButtons.some((element) => { return element.method == 'doEdit' }) && buttons_create.push(
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@gaotgg@doEdit`} key="doEdit" style={{ display: previewButtons.some((element) => { return element.method == 'doEdit' }) ? 'inline-block' : 'none' }} type="primary" onClick={() => this.doEdit()}>{previewButtons.map((e) => { if (e.method == 'doEdit') { return e.title } else { return '' } })}</Button>,
        )
        previewButtons.some((element) => { return element.method == 'doFinish' }) && buttons_create.push(
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@mwg654@doFinish`} key="doFinish" style={{ display: previewButtons.some((element) => { return element.method == 'doFinish' }) ? 'inline-block' : 'none' }} type="primary" loading={this.state.finishLoading} disabled={this.state.finishLoading || this.state.deleteLoading} onClick={() => this.doFinish()}>{previewButtons.map((e) => { if (e.method == 'doFinish') { return e.title } else { return '' } })}</Button>,
        )
        previewButtons.some((element) => { return element.method == 'doDelete' }) && buttons_create.push(
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@47iftv@doDelete`} key="doDelete" style={{ display: previewButtons.some((element) => { return element.method == 'doDelete' }) ? 'inline-block' : 'none' }} type="primary" loading={this.state.deleteLoading} disabled={this.state.finishLoading || this.state.deleteLoading} onClick={() => this.doDelete()}>{previewButtons.map((e) => { if (e.method == 'doDelete') { return e.title } else { return '' } })}</Button>,
        )
        previewButtons.some((element) => { return element.method == 'doShare' }) && buttons_create.push(
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@v61hzw@doShare`} key="doShare" style={{ display: previewButtons.some((element) => { return element.method == 'doShare' }) ? 'inline-block' : 'none' }} type="primary" onClick={() => this.doShare()}>{previewButtons.map((e) => { if (e.method == 'doShare') { return e.title } else { return '' } })}</Button>,
        )
        previewButtons.some((element) => { return element.method == 'doValuate' }) && buttons_create.push(
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@s96ugn@doValuate`} key="doValuate" style={{ display: previewButtons.some((element) => { return element.method == 'doValuate' }) ? 'inline-block' : 'none' }} type="primary" onClick={() => this.doValuate()}>{previewButtons.map((e) => { if (e.method == 'doValuate') { return e.title } else { return '' } })}</Button>,
        )
        previewButtons.some((element) => { return element.method == 'doConvert' }) && buttons_create.push(
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@1ud9ty@doConvert`} key="doConvert" style={{ display: previewButtons.some((element) => { return element.method == 'doConvert' }) ? 'inline-block' : 'none' }} type="primary" onClick={() => this.doConvert()}>{previewButtons.map((e) => { if (e.method == 'doConvert') { return e.title } else { return '' } })}</Button>,
        )
        // previewButtons.some((element) => { return element.method == 'doLog' }) && buttons_create.push(
        //   <Button key="doLog" style={{ display: previewButtons.some((element) => { return element.method == 'doLog' }) ? 'inline-block' : 'none' }} type="primary" onClick={() => this.toggleLog()}>{previewButtons.map((e) => { if (e.method == 'doLog') { return e.title } else { return '' } })}</Button>,
        // )
      }
      let buttonsCreate = (previewButtons && previewButtons.length > 0 && hasRight && hasSecretRight&&hasDataRight) ? buttons_create : [];
      return buttonsCreate;
    }
    if (type == 'create') {
      let buttonsCreate = [
        (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@hxttrr@create`} type="primary" loading={saveLoading} disabled={saveLoading} onClick={() => { this.handleSubmit() }}>{getLabel(30986,'保存')}</Button>),
      ];

      return buttonsCreate;
    }
    if (type == 'edit') {
      let buttonsCreate = [
        (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@3532dm@edit`} type="primary" loading={saveLoading} disabled={saveLoading} onClick={() => { this.editSave() }}>{getLabel(30986,'保存')}</Button>),
        
      ];
       if(!this.state.needHideBack){
        buttonsCreate.push((<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@k0geah@needHideBack`} type="ghost" disabled={saveLoading} onClick={() => { this.doReturn() }}>{getLabel(1290,'返回')}</Button>));
       }

      return buttonsCreate;
    }
    if (type == 'share') {
      let buttonsCreate = [
        // (<Button type="primary" disabled={false} onClick={()=>{this.addShare()}}>添加</Button>),
        // (<Button type="primary" disabled={false} onClick={()=>{this.deledtShare()}}>删除</Button>),
        (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@o2kwqu@share`} type="ghost" disabled={false} onClick={() => { this.doReturn() }}>{getLabel(1290,'返回')}</Button>),
      ];

      return buttonsCreate;
    }
  }

  doEdit = () => {
    const {setCreateCondition,setParam,getBaseFields,fromType}= this.props.createWorkPlanStore
    const {setStatusParams}= this.props.myWorkPlanStore
    this.setState({ spinning: true })
    let _this = this;
    getBaseFields({workid: this.props.workPlanId,fromType:fromType},this.setEdit)
  }

  setEdit = ()=>{
    const {setParam}= this.props.createWorkPlanStore
    const {setStatusParams}= this.props.myWorkPlanStore
    setParam({workPlanId :this.props.workPlanId,type:'edit'});
    setStatusParams({createType:'edit'})
    this.setState({spinning: false })
  }

  handleSubmit = () => {
    let {form,memberConflict,memberConflictChk,uploadParams,uploadKeys}=this.props.createWorkPlanStore;
    const{changeGetCalendarData}=this.props.myWorkPlanStore;
    uploadParams = toJS(uploadParams);
    uploadKeys = toJS(uploadKeys);
    let alldatas = form.getFormParams();
    uploadKeys.map(key => {//上传附件字段相应的参数单独放入
      let uploadVal = [];
      uploadParams[key].datas.map(item=>{
        uploadVal.push(item.fileid)
      })
      alldatas = {
        ...alldatas,
        [key]: uploadVal.join(",")
      }
    })
    let canSave = true;
    let { beginDateTime, endDateTime, beginTime, endTime, remindType, remindBeforeStart, remindBeforeEnd, remindImmediately } = alldatas
    if (beginDateTime >= endDateTime) {
      Modal.warning({
        title: `${getLabel(127354,'警告')}`,
        content: `${getLabel('31832','结束时间必须大于开始时间')}`,
      });
      return
    } 
    if(remindType !== '' && (remindBeforeStart == 0 && remindBeforeEnd == 0 && (remindImmediately == 0 || remindImmediately === undefined || remindImmediately === ''))){
      Modal.warning({
        title: `${getLabel(127354,'警告')}`,
        content: `${getLabel(20238,'日程提醒时间未被选定！')}`,
      });
      return
    }
   
    let _this = this;
    form.validateForm().then(f => {
      if(f.isValid) {
        if(remindType === '') { // 未选择提醒方式时，清空开始前/结束前选中
          alldatas.remindBeforeStart = '0';
          alldatas.remindBeforeEnd = '0';
        }
        if( memberConflictChk==1 ){
          let params = {
            workid:this.props.workPlanId&&this.props.workPlanId,
            beginDateTime:alldatas.beginDateTime,
            endDateTime:alldatas.endDateTime,
            resourceId:alldatas.memberIDs,
          }
          this.doCheck(params,alldatas)
        }else if( memberConflictChk==0 ){
          this.doSubmit(alldatas)
        }
      }else{
        f.showErrors()
      }
    })
  }

  // 关闭无侵入开发等打开的iframe弹框
  closeIframe = () => {
    if(top && top.window && top.window.getParentDialog) {
      var dialog = top.window.getParentDialog();
      if(dialog && dialog.props && dialog.props.url && dialog.props.url.indexOf('main/wp/workPlanCreateSingle') > -1) {
        dialog.close();
        dialog.callback();	//此时如果调用方函数逻辑耗时长或报错，体验就是无响应
      }
    }
  }

  doSubmit = (alldatas)=>{
    const {doInit}=this.props
    const{changeGetCalendarData}=this.props.myWorkPlanStore;
    let {type,oldMemberIds}=this.props.createWorkPlanStore;
    let _this = this;
    //标识从日程模块新建的信息,目的是开启接收人范围的时候进行控制
    alldatas = {...alldatas,from:'workplan'}
    if(type == 'create'){
      let {setSaveLoading}= this.props.myWorkPlanStore;
      let {isSingle}= this.props.createWorkPlanStore;
      const { push } = this.props.routing;
      setSaveLoading(true);
      //前端对新建的时候已经做过处理,并且后端也做了控制,新建的时候就不需要confirm确认
      WeaTools.callApi('/api/workplan/base/add', 'POST', alldatas).then((result) => {
        setSaveLoading(false);
        if(result&&result.status){
          if(result.error && result.outList){
            message.error(`${result.error}`);
          }else{
            doInit&&doInit()
            // changeGetCalendarData(); // 刷新
            if(isSingle){//刷新. 查看
              const query = {
                workPlanId: result.workplanid,
                type:'preview'
              };
            
              if(_this.props && _this.props.isBtnDown) {
                _this.closeIframe();
              } else {
                push({
                  pathname: '/main/wp/workPlanCreateSingle',
                  query,
                });
              }

            }else{
              _this.doClose()//关闭弹出框
            }
            _this.props.changeOneWeekDatas && _this.props.changeOneWeekDatas();
          }
          
        }else{
          message.error(`${getLabel(22620,'保存失败')}`);
        }
        
      }, () => {
        setSaveLoading(false);
      })
    }else if (type == 'edit') {
      let {setSaveLoading}= this.props.myWorkPlanStore;
      let {isSingle}= this.props.createWorkPlanStore;
      const { push } = this.props.routing;
      setSaveLoading(true);
      alldatas = { ...alldatas, workid: this.props.workPlanId }
      //编辑的情况下需要考虑是否人员变动,如果人员变动了,那么就需要needCheck=1
      if(oldMemberIds != alldatas.memberIDs){
        alldatas = {...alldatas,needCheck:1}
      }else{
        alldatas = {...alldatas,needCheck:0}
      }
      let doSuccess = ()=>{
        changeGetCalendarData(); //刷新
        setSaveLoading(false);
        if(isSingle){
          const query = {
            workPlanId: _this.props.workPlanId,
            type:'preview'
          };

          if(_this.props && _this.props.isBtnDown) {
            _this.closeIframe();
          } else {
            push({
              pathname: '/main/wp/workPlanCreateSingle',
              query,
            });
          }

        }else{
          _this.doClose()//关闭弹出框
        }
        _this.props.changeOneWeekDatas && _this.props.changeOneWeekDatas();
      }
      WeaTools.callApi('/api/workplan/base/add', 'POST', alldatas).then((result) => {
        if(!result.error){
          doInit&&doInit();
          doSuccess();
        }else if(result.error && result.outList){
          setSaveLoading(false);
          let controlMsg = '';
          let cont = <div>{result.error}{getLabel(510186,'如果继续保存，以上人员将会从“接收人”中删除！')}</div>
          controlMsg = (
            <div style={{marginRight: '-20px'}}>
              <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@ssbr0d`} height='80px'>
                {cont}
              </WeaNewScroll>
            </div>
          )
          Modal.confirm({
            title: getLabel(15172,'系统提示'),
            content: controlMsg,
            onOk() {
              alldatas = {...alldatas,needCheck:0}
              WeaTools.callApi('/api/workplan/base/add', 'POST', alldatas).then((result) => {
                if(!result.error){
                  doInit&&doInit();
                  doSuccess();
                }
              }, () => {
                
              })
            },
          })
        }
      }, () => {
        setSaveLoading(false);
      })
    }
  }

  doCheck = (params,alldatas)=>{
    WeaTools.callApi('/api/workplan/base/workplanMemberChk','POST',params).then((ret)=>{
      if(ret.chkstatus){
        this.doMemberTip(ret,alldatas)
      }else{
        this.doSubmit(alldatas)
      }
    })
  }

  doMemberTip = ( result,alldatas) => {
    let that = this
    let conflictMsg = '';
    let cont = result.hrms.map((e) => {
      return <div>{e}</div>
    })
    conflictMsg = (
      <div style={{marginRight: '-20px'}}>
        <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@ada1va`} height='80px'>
          {cont}
        </WeaNewScroll>
      </div>
    )
    if (result.cansub == true) {
      Modal.confirm({
        title: getLabel(504401, '以下日程冲突，确定要继续保存吗？'),
        content: conflictMsg,
        onOk() {
          that.doSubmit(alldatas)
        },
      })
    } else {
      Modal.warning({
        title: getLabel(504398, '日程冲突不能保存'),
        content: conflictMsg,
      })
    }

  }

  editSave = () => {
    //走编辑-保存的接口---或者直接调用this.handleSubmit();
    this.handleSubmit();
  }
  doFinish = () => {
    const{doInit}=this.props;
    const { isCreater } = this.props.createWorkPlanStore;
    const{changeGetCalendarData}=this.props.myWorkPlanStore;
    let _this = this;
    const { workPlanId,createrID } = this.props;
    let contentDom = null;
    let mycheck = '0';
    let content=getLabel(387046,'确认完成吗？');
    const style1 = {
      paddingBottom: '10px',
      paddingLeft: '0px',
      paddingTop: '15px'
    };
    const style2 = {
      paddingBottom: '15px'
    };
    if(isCreater){
      contentDom = (
        <div>
          <div class='ant-confirm-content wdb wea-f14' style={ style1 }>{getLabel(387046,'确认完成吗？')}</div>
          <div style={style2}>
            <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@298u2p`} 
              value = { mycheck }
              onChange={value => {
                mycheck = value;
            }}/>
            <span style={{ fontSize: '14px',paddingLeft: '7px' }}>{getLabel(520269,'给接收人发送已完成的消息中心提醒')}</span></div>
        </div>
      )
    }else{
      contentDom = (
        <div>
          <div class='ant-confirm-content wdb wea-f14' style={{ paddingLeft: '0px' }}>{getLabel(387046,'确认完成吗？')}</div>
        </div>
      )
    }
    Modal.confirm({
      title: `${getLabel(131329,'信息确认')}`,
      content: contentDom,
      onOk() {
        let alldatas = { workid: workPlanId, isRemind: mycheck }
        _this.setState({ finishLoading: true })
        WeaTools.callApi('/api/workplan/base/finish', 'POST', alldatas).then((result) => {
          _this.setState({ finishLoading: false });
          let {isSingle,setParam, getViewFields, workPlanId}= _this.props.createWorkPlanStore;
          const { push } = _this.props.routing;
          doInit&&doInit()
          changeGetCalendarData&&changeGetCalendarData();
          if(isSingle){
             //更新按钮
             if(_this.props && _this.props.isBtnDown) {
              _this.closeIframe();
            } else {
             if(result.btn){
              setParam({previewButtons:result.btn});
             }
             getViewFields({workid: workPlanId});
            }
          } else {
            _this.doClose()//关闭弹出框
          }
          _this.props.changeOneWeekDatas && _this.props.changeOneWeekDatas();
        })
      },
      onCancel() { },
  });
    
  }
  doDelete = () => {
    const {doInit} = this.props
    const{changeGetCalendarData}=this.props.myWorkPlanStore;
    let _this = this;
    const { workPlanId } = this.props;
    let {isSingle,setParam,getViewFields}=this.props.createWorkPlanStore;
    const { push } = this.props.routing;
    let alldatas = { workid: workPlanId }
    Modal.confirm({
        title: `${getLabel(131329,'信息确认')}`,
        content: `${getLabel(15097,'确定要删除吗?')}`,
        onOk() {
            _this.setState({ deleteLoading: true })
            WeaTools.callApi('/api/workplan/base/delete', 'POST', alldatas).then((result) => {
                _this.setState({ deleteLoading: false })
                if(result.status){
                  message.success(`${getLabel(30700,'操作成功')}`);
                  doInit&&doInit()
                  changeGetCalendarData&&changeGetCalendarData();
                  if(isSingle){
                    if(_this.props && _this.props.isBtnDown) {
                      _this.closeIframe();
                    } else {
                      getViewFields({workid: workPlanId}, () => setParam({type:'preview'}));
                    }
                  }else{
                    _this.doClose()//关闭弹出框
                  }
                  _this.props.changeOneWeekDatas && _this.props.changeOneWeekDatas();
                }else{

                }
            })
        },
        onCancel() { },
    });

  }
  doShare = () => {
    const {setParam}= this.props.createWorkPlanStore
    setParam({type:'share'});
    //弹出共享页面
  }

  chatShare = () => {
    const {setParam}= this.props.createWorkPlanStore
    setParam({chatVisible:true});
  }

  doValuate = () => {
    const { workPlanId } = this.props;
    let alldatas = { workid: workPlanId }
    let _this = this;
    WeaTools.callApi('/api/workplan/base/finish', 'POST', alldatas).then((result) => {
      _this.props.changeOneWeekDatas && _this.props.changeOneWeekDatas();
    })
    this.doClose()//关闭弹出框
  }
  doConvert = () => {
    const { workPlanId } = this.props;
    let alldatas = { workid: workPlanId }
    let _this = this;
    WeaTools.callApi('/api/workplan/base/', 'POST', alldatas).then((result) => {
      _this.props.changeOneWeekDatas && _this.props.changeOneWeekDatas();
    })
    this.doClose()//关闭弹出框
  }
  doReturn = () => {
    const {status,open}= this.props.myWorkPlanStore
    const {workPlanId} = toJS(status)   
    open('preview',workPlanId);
    
    const {setParam}= this.props.createWorkPlanStore
    setParam({type:'preview'});
    
  }
  deledtShare = () => {
    //共享里的删除
    let _this = this;
    let { dataKey, comsWeaTableStore, doGetShareTable } = this.props.myWorkPlanStore;
    let { workPlanId } = this.props;
    comsWeaTableStore = toJS(comsWeaTableStore);
    const tableNow = comsWeaTableStore.state[dataKey.split('_')[0]] || comsWeaTableStore.state['init'];
    if (tableNow.selectedRowKeys.length == 0) {
      Modal.warning({
        title: `${getLabel(127354,'警告')}`,
        content: `${getLabel(32568,'请选择要删除的记录!')}`,
      });
    } else if (tableNow.selectedRowKeys.length > 0) {
      let keys = tableNow.selectedRowKeys.join(',');
      let values = { delid: keys, planID: workPlanId };
      Modal.confirm({
        title: `${getLabel(131329,'信息确认')}`,
        content: `${getLabel(15097,'确定要删除吗?')}`,
        onOk() {
          _this.setState({ spinning: true })
          WeaTools.callApi('/api/workplan/share/deleteWorkPlanShare', 'POST', values).then((result) => {
            if (result.status) {
              doGetShareTable(workPlanId);
              _this.setState({ spinning: false })
            }
          })
        },
        onCancel() { },
      });
    }
  }
  addShare = () => {
    //共享里的添加
    WeaTools.callApi('/api/workplan/share/getShareAuthField', 'POST', {}).then((result) => {
      this.setState({ authConditions: result, authVisible: true })
    })
  }
  callbackState = (obj) => {
    // this.setState({authConditions:result,authVisible:true})
    this.setState(obj)

  }
  onCancel = () => {
    this.setState({ authConditions: [], authVisible: false })
  }
  spinning = (bool) => {
    this.setState({ spinning: bool })
  }
}
//打开附件
window.openWorkplanDiscussDoc = (t, showid, workplanid) => {
  openFullWindowHaveBar(`/spa/document/index2file.jsp?id=${showid}&isOpenFirstAss=1&workplanid=${workplanid}`);
}
//打开附件
window.openWorkplanDiscussDownload = (t, showid, workplanid) => {
  window.open(`/weaver/weaver.file.FileDownload?fileid=${showid}&download=1&workplanid=${workplanid}`)
}

window.openWorkplanAppLink = (linkType, linkid, workplanid, isPro=false) => {
  if (linkType == "doc")
    window.open(`/spa/document/index.jsp?id=${linkid}&workplanid=${workplanid}`)
  else if (linkType == "task")
    window.open(`/spa/prj/index.html#/main/prj/taskCard?taskid=${linkid}`)
  else if (linkType == "crm")
    window.open(isPro?`/CRM/manage/customer/CustomerBaseView.jsp?CustomerID=${linkid}`:`/spa/crm/static/index.html#/main/crm/customerView?customerId=${linkid}`)
  else if (linkType == "workflow")
    window.open(`/spa/workflow/static4form/index.html#/main/workflow/req?fromModul=workplan&modulResourceId=${workplanid}&requestid=${linkid}`)
  else if (linkType == "project")
    window.open(`/spa/prj/index.html#/main/prj/projectCard?prjid=${linkid}`)
  else 
    return false;
}

export default WorkPlanCreate
